//
//  YLCEasyVideoListViewController.m
//  LinYa
//
//  Created by 初程程 on 2018/5/7.
//  Copyright © 2018年 初程程. All rights reserved.
//

#import "YLCEasyVideoListViewController.h"
#import "YLCVideoTrainCell.h"
#import "ShootVideoViewController.h"
#import "YLCNavigationViewController.h"
#import "YLCSendVideoNextViewController.h"

#define VIDEO_CELL   @"YLCVideoTrainCell"
@interface YLCEasyVideoListViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,ZFPlayerDelegate,UIActionSheetDelegate>
@property (nonatomic, strong) ZFPlayerControlView *controlView;
@end

@implementation YLCEasyVideoListViewController
{
    UICollectionView *videoTable;
    NSArray *videoDataList;
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
    [self initDataSourse];

}
- (UIBarButtonItem *)rightBarButtonItem{
    
    return [YLCFactory createTitleBarButtonItemWithTitle:@"添加视频" titleColor:RGB(255, 255, 255) selector:@selector(gotoAddVideo) target:self];
}
- (void)gotoAddVideo{
    UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"相机",@"相册", nil];
    
    [sheet showInView:self.view];

}
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex==0) {
        [self gotoVideo];
    }
    if (buttonIndex==1) {
        [self gotoAlbum];
    }
}
- (void)gotoVideo{
    ShootVideoViewController *con = [[ShootVideoViewController alloc] init];
    
    con.isEasy = YES;
    
    con.classifyId = _classifyId;
    
    YLCNavigationViewController *nav  = [[YLCNavigationViewController alloc] initWithRootViewController:con];
    
    if (self.presentedViewController != nil) {
        [(UINavigationController *)self dismissViewControllerAnimated:NO completion:nil];
    }
    
    [self presentViewController:nav animated:YES completion:nil];
}
- (void)gotoAlbum{
    HXAlbumListViewController *con = [[HXAlbumListViewController alloc] init];
    
    HXPhotoManager *manager = [[HXPhotoManager alloc] initWithType:HXPhotoManagerSelectedTypeVideo];
    manager.configuration.openCamera = NO;
    
    manager.configuration.photoMaxNum = 1;
    
    con.manager = manager;
    
    con.doneBlock = ^(NSArray<HXPhotoModel *> *allList, NSArray<HXPhotoModel *> *photoList, NSArray<HXPhotoModel *> *videoList, BOOL original, HXAlbumListViewController *viewController) {
        HXPhotoModel *photoModel = videoList[0];
        [self getVideoFromPHAsset:photoModel.asset photoModel:photoModel];
    };
    
    if (self.presentedViewController != nil) {
        [self dismissViewControllerAnimated:NO completion:nil];
    }
    HXCustomNavigationController *nav = [[HXCustomNavigationController alloc] initWithRootViewController:con];
    
    [self presentViewController:nav animated:YES completion:nil];
}
- (CGFloat) getFileSize:(NSString *)path{
    NSLog(@"%@",path);
    NSFileManager *fileManager = [NSFileManager defaultManager];
    float filesize = -1.0;
    if ([fileManager fileExistsAtPath:path]) {
        NSDictionary *fileDic = [fileManager attributesOfItemAtPath:path error:nil];//获取文件的属性
        unsigned long long size = [[fileDic objectForKey:NSFileSize] longLongValue];
        filesize = 1.0*size/1024;
    }else{
        NSLog(@"找不到文件");
    }
    return filesize;
}
- (void)getVideoFromPHAsset:(PHAsset *)asset
                 photoModel:(HXPhotoModel *)photoModel{
    NSArray *assetResources = [PHAssetResource assetResourcesForAsset:asset];
    PHAssetResource *resource;
    
    for (PHAssetResource *assetRes in assetResources) {
        if (@available(iOS 9.1, *)) {
            if (assetRes.type == PHAssetResourceTypePairedVideo ||
                assetRes.type == PHAssetResourceTypeVideo) {
                resource = assetRes;
            }
        } else {
            // Fallback on earlier versions
        }
    }
    NSString *fileName = @"tempAssetVideo.mov";
    if (resource.originalFilename) {
        fileName = resource.originalFilename;
    }
    
    PHVideoRequestOptions *options = [[PHVideoRequestOptions alloc] init];

    options.version = PHImageRequestOptionsVersionCurrent;

    options.deliveryMode = PHVideoRequestOptionsDeliveryModeAutomatic;

    PHImageManager *manager = [PHImageManager defaultManager];

    NSDateFormatter *formater = [[NSDateFormatter alloc] init];//用时间给文件全名，以免重复
    [formater setDateFormat:@"yyyyMMddHHmmss"];
    NSString *nowTimeStr = [formater stringFromDate:[NSDate dateWithTimeIntervalSinceNow:0]];
    NSString *fileNames = [nowTimeStr stringByAppendingString:@"merge.mp4"];
    NSString *PATH_MOVIE_FILE_MP4 = [NSTemporaryDirectory() stringByAppendingPathComponent:fileNames];
    
    [manager requestExportSessionForVideo:asset options:options exportPreset:AVAssetExportPresetMediumQuality resultHandler:^(AVAssetExportSession * _Nullable exportSession, NSDictionary * _Nullable info) {
        exportSession.outputURL = [NSURL fileURLWithPath:PATH_MOVIE_FILE_MP4];
        exportSession.shouldOptimizeForNetworkUse = NO;
        exportSession.outputFileType = AVFileTypeMPEG4;
        [exportSession exportAsynchronouslyWithCompletionHandler:^{

            if ([exportSession status] == AVAssetExportSessionStatusCompleted) {
                
                dispatch_async(dispatch_get_main_queue(),^{
                    YLCSendVideoNextViewController *con = [[YLCSendVideoNextViewController alloc] init];
                    con.videoPath = photoModel.fileURL;
                    con.classifyId = _classifyId;
                    con.isEasy = YES;
                    con.isAlbum = YES;
                    con.mp4VideoPath = PATH_MOVIE_FILE_MP4;
                    CGFloat f = [self getFileSize:PATH_MOVIE_FILE_MP4];
                    NSLog(@"%f",f);
                    [self.navigationController pushViewController:con animated:YES];
                });
            }
        }];
    }];
}

- (void)test:(NSString*)sourceUrl{
    AVURLAsset *avAsset = [AVURLAsset URLAssetWithURL:[NSURL fileURLWithPath:sourceUrl] options:nil];
    NSArray *compatiblePresets = [AVAssetExportSession exportPresetsCompatibleWithAsset:avAsset];
    NSLog(@"%@",compatiblePresets);
    if ([compatiblePresets containsObject:AVAssetExportPresetHighestQuality]) {
        AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:avAsset presetName:AVAssetExportPresetMediumQuality];
        NSDateFormatter *formater = [[NSDateFormatter alloc] init];//用时间给文件全名，以免重复
        [formater setDateFormat:@"yyyyMMddHHmmss"];
        NSString * resultPath = [NSHomeDirectory() stringByAppendingFormat:@"/Documents/output-%@.mp4", [formater stringFromDate:[NSDate date]]];
        NSLog(@"resultPath = %@",resultPath);
        exportSession.outputURL = [NSURL fileURLWithPath:resultPath];
        
        exportSession.outputFileType = AVFileTypeMPEG4;
        
        exportSession.shouldOptimizeForNetworkUse = YES;
        
        [exportSession exportAsynchronouslyWithCompletionHandler:^(void){
             switch (exportSession.status) {
                 case AVAssetExportSessionStatusUnknown:
                     NSLog(@"AVAssetExportSessionStatusUnknown");
                     break;
                 case AVAssetExportSessionStatusWaiting:
                     NSLog(@"AVAssetExportSessionStatusWaiting");
                     break;
                 case AVAssetExportSessionStatusExporting:
                     NSLog(@"AVAssetExportSessionStatusExporting");
                     break;
                 case AVAssetExportSessionStatusCompleted:
                     NSLog(@"AVAssetExportSessionStatusCompleted");
                     break;
                 case AVAssetExportSessionStatusFailed:
                     NSLog(@"AVAssetExportSessionStatusFailed");
                     break;
                 case AVAssetExportSessionStatusCancelled:
                     NSLog(@"AVAssetExportSessionStatusCancelled");
                     break;
             }
         }];
    }
}


- (void)viewDidLoad {
    [super viewDidLoad];
//    [self initDataSourse];
    [self createCustomView];
}
- (void)initDataSourse{
    YLCAccountModel *userModel = [[YLCAccountManager shareManager] currentAccount];
    [YLCNetWorking loadNetServiceWithParam:@{@"userId":userModel.user_id,@"token":userModel.token,@"classifyId":_classifyId} method:@"POST" urlPath:@"app/sygt/video" delegate:self response:^(id responseObject, NSError *error) {
        if (error) {
            return ;
        }
        videoDataList = responseObject;
        
        [videoTable reloadData];
    }];

}
- (void)createCustomView{
    UICollectionViewFlowLayout *flow = [[UICollectionViewFlowLayout alloc] init];
    
    flow.minimumLineSpacing = 10;
    
    videoTable = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:flow];
    
    videoTable.backgroundColor = YLC_COMMON_BACKCOLOR;
    
    [videoTable registerClass:[YLCVideoTrainCell class] forCellWithReuseIdentifier:VIDEO_CELL];
    
    videoTable.delegate = self;
    
    videoTable.dataSource = self;
    
    [self.view addSubview:videoTable];

    [videoTable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(UIEdgeInsetsZero);
    }];
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if (JK_IS_ARRAY_NIL(videoDataList)) {
        return 0;
    }
    return videoDataList.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    YLCVideoTrainCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:VIDEO_CELL forIndexPath:indexPath];
    
    if (indexPath.row < videoDataList.count) {
        cell.dict = videoDataList[indexPath.row];
        
        UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPress:)];
        longPress.minimumPressDuration = 1.0;
        [cell.contentView addGestureRecognizer:longPress];
        
        WS(weakSelf)
        __block UICollectionView *weakCollectionView = collectionView;
        __block NSDictionary *dict = videoDataList[indexPath.row];
        __block NSIndexPath *weakIndexPath = indexPath;
        __block YLCVideoTrainCell *weakCell     = cell;
        cell.playBlock = ^(UIButton *btn){
            
            
            NSMutableDictionary *dic = @{@"高清":dict[@"site"]}.mutableCopy;
            //        for (ZFVideoResolution * resolution in model.playInfo) {
            //            [dic setValue:resolution.url forKey:resolution.name];
            //        }
            // 取出字典中的第一视频URL
            NSURL *videoURL = [NSURL URLWithString:dict[@"site"]];
            ZFPlayerModel *playerModel = [[ZFPlayerModel alloc] init];
            playerModel.title            = dict[@"title"];
            playerModel.videoURL         = videoURL;
            playerModel.placeholderImageURLString = dict[@"cover"];
            playerModel.placeholderImage = [UIImage imageNamed:@"image_placeholder"];
            playerModel.scrollView       = weakCollectionView;
            playerModel.indexPath        = weakIndexPath;
            // 赋值分辨率字典
            playerModel.resolutionDic    = dic;
            // player的父视图tag
            playerModel.fatherViewTag    = weakCell.posterView.tag;
            
            // 设置播放控制层和model
            [weakSelf.playerView playerControlView:nil playerModel:playerModel];
            // 下载功能
            weakSelf.playerView.hasDownload = NO;
            // 自动播放
            [weakSelf.playerView autoPlayTheVideo];
        };
    }
    
    return cell;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return CGSizeMake(self.view.frameWidth, self.view.frameWidth*9/16);
}
#pragma mark  实现成为第一响应者方法
-(BOOL)canBecomeFirstResponder{
    return YES;
}
#pragma mark -- 易沟通视频删除
- (void)longPress:(UILongPressGestureRecognizer*)press{
    
    if (press.state == UIGestureRecognizerStateBegan) {
        //成为第一响应者，需重写该方法
        [self becomeFirstResponder];
        
        CGPoint location = [press locationInView:videoTable];
        
        NSIndexPath * indexPath = [videoTable indexPathForItemAtPoint:location];
        
        NSDictionary *dict = videoDataList[indexPath.row];
        
        YLCAccountModel *userModel = [[YLCAccountManager shareManager] currentAccount];
        
        [YLCHUDShow showSelectAlertWithTarget:self Message:@"是否确认删除" leftTitle:@"确认" rightTitle:@"取消" selector:^(NSInteger index) {
            if (index==0) {
                
                NSDictionary *parms = @{@"userId":userModel.user_id,
                                        @"token":userModel.token,
                                        @"videoId":dict[@"id"],
                                        @"classifyId":_classifyId,
                                        };
                
                [YLCNetWorking loadNetServiceWithParam:parms method:@"POST" urlPath:@"app/sygt/delVideo" delegate:self response:^(id responseObject, NSError *error) {
                    if (error) {
                        return ;
                    }
                    [SVProgressHUD showSuccessWithStatus:@"删除成功"];
                    
                    NSMutableArray *container = [videoDataList mutableCopy];
                    
                    [container removeObject:dict];
                    
                    videoDataList = [container copy];
                    
                    [videoTable reloadData];
                }];
            }
        }];
    }
}
- (ZFPlayerView *)playerView {
    if (!_playerView) {
        _playerView = [ZFPlayerView sharedPlayerView];
        _playerView.delegate = self;
        
        _playerView.cellPlayerOnCenter = NO;
        
        _playerView.forcePortrait = NO;
        
        _playerView.stopPlayWhileCellNotVisable = YES;
        
//        ZFPlayerShared.isLockScreen = YES;
        ZFPlayerShared.isStatusBarHidden = NO;
    }
    return _playerView;
}

- (ZFPlayerControlView *)controlView {
    if (!_controlView) {
        _controlView = [[ZFPlayerControlView alloc] init];
    }
    return _controlView;
}
- (NSString *)title{
    return @"视频";
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
